const express = require('express');
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');

const app = express();

// 检查 Python 环境并获取股票数据
function getStockData(pythonCode, res) {
  // 尝试多个 Python 路径
  const pythonPaths = [
    '/usr/local/bin/python3',
    '/usr/bin/python3',
    'python3',
    'python'
  ];

  let pythonProcess;
  let foundPython = false;

  for (const pythonPath of pythonPaths) {
    try {
      // 检查 Python 是否存在
      const child = spawn(pythonPath, ['--version']);
      child.on('error', (error) => {
        // 如果当前路径失败，尝试下一个路径
        return;
      });
      child.on('close', (code) => {
        if (code === 0 && !foundPython) {
          // 找到可用的 Python，启动数据获取进程
          foundPython = true;
          pythonProcess = spawn(pythonPath, ['-c', pythonCode]);
          handlePythonProcess(pythonProcess, res);
        }
      });
      break; // 只检查第一个可用的 Python
    } catch (error) {
      continue; // 继续尝试下一个路径
    }
  }

  // 如果所有路径都失败，返回错误
  setTimeout(() => {
    if (!foundPython) {
      res.status(500).json({ error: '未找到可用的 Python 环境' });
    }
  }, 5000);
}

function handlePythonProcess(pythonProcess, res) {
  let data = '';
  
  pythonProcess.stdout.on('data', (chunk) => {
    data += chunk;
  });

  pythonProcess.on('close', (code) => {
    if (code === 0) {
      try {
        const stockData = JSON.parse(data);
        res.json(stockData);
      } catch (e) {
        res.status(500).json({ error: '解析数据失败: ' + e.message });
      }
    } else {
      res.status(500).json({ error: '获取数据失败，退出码: ' + code });
    }
  });

  pythonProcess.stderr.on('data', (data) => {
    console.error(`stderr: ${data}`);
  });
}

// 获取A股股票数据
app.get('/api/stocks/a-shares', (req, res) => {
  const pythonCode = `
try:
    import akshare as ak
    import json

    # 获取A股股票信息
    stocks = ak.stock_zh_a_spot_em()
    # 选择需要的字段
    result = stocks[['代码', '名称']].to_dict('records')
    print(json.dumps(result, ensure_ascii=False))
except Exception as e:
    print(f"Error: {str(e)}")
  `;
  
  getStockData(pythonCode, res);
});

// 获取港股股票数据
app.get('/api/stocks/hk-shares', (req, res) => {
  const pythonCode = `
try:
    import akshare as ak
    import json

    # 获取港股股票信息
    stocks = ak.stock_hk_spot_em()
    # 选择需要的字段
    result = stocks[['代码', '名称']].to_dict('records')
    print(json.dumps(result, ensure_ascii=False))
except Exception as e:
    print(f"Error: {str(e)}")
  `;
  
  getStockData(pythonCode, res);
});

module.exports = app;